package com.gqzdev.xblog.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @ClassName: FileUploadUtil
 * @author: ganquanzhong
 * @date: 2020/6/8 13:41
 */
@Component
public class FileUploadUtil {

    @Value("${xblog.file.path}")
    private String filePath;

    @Value("${xblog.file.imageUrlPrefix}")
    private String imageUrlPrefix;

    public List<Map<String, Object>> ueditorUpload(String[] sources) throws Exception {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < sources.length; i++) {

//            System.out.println("--->>>>" + sources[i]);
            //转换URL
            URL imgURL = new URL(sources[i].trim());
            //打开链接
            HttpURLConnection urlConn = (HttpURLConnection) imgURL.openConnection();
            // 模拟浏览器请求
            urlConn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36");

            // 连接
            urlConn.connect();
            //返回的状态码是200 表示成功
            if (urlConn.getResponseCode() == 200) {

                System.out.println(urlConn.getContentType());
                //网络中文件存放位置！

                //获取输入流,从网站读取数据到 内存中
                InputStream ins = urlConn.getInputStream();
                //得到图片的二进制数据，以二进制封装得到数据，具有通用性
                byte[] data = readInputStream(ins);
                String type="png";
                String middlePath = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
                String filename = System.currentTimeMillis() +"."+type;
                // 上传存放位置
                String fileFullName = filePath + middlePath + filename;

                //new一个文件对象用来保存图片，默认保存当前工程根目录
                File imageFile = new File(fileFullName);
                //创建输出流
                FileOutputStream outStream = new FileOutputStream(imageFile);
                //写入数据
                outStream.write(data);
                //关闭输出流
                outStream.close();

                // 图片访问地址（tomcat服务器） OOS  this.aliyunConfig.getUrlPrefix() + filePath
                String image_url = imageUrlPrefix +middlePath+ filename;
                try {
                    //ossClient.putObject(aliyunConfig.getBucketName(),filePath , ins ,metadata);
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("source",sources[i]);
                    map.put("state", "SUCCESS");
                    map.put("original", filename);
//                    map.put("size", size);
                    map.put("title", filename);
                    map.put("type", type);
                    map.put("url", image_url);
                    result.add(map);
                } catch (Exception e) {
                    System.out.println("上传失败");
                }
            }
        }
        return result;
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    public static void main(String[] args){
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
//        String[] source = {"https://upload-images.jianshu.io/upload_images/8928647-6d59dcabb90e643e.png?imageMogr2/auto-orient/strip|imageView2/2/w/906/format/webp"};
        String[] source = {"https://user-gold-cdn.xitu.io/2020/6/7/1728e1d66873225c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1"};
        try {
            List<Map<String, Object>> maps = fileUploadUtil.ueditorUpload(source);
            System.out.println(JSON.toJSONString(maps));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
